package com.lzd.pgyuploader.utils

import java.util.concurrent.TimeUnit

class ExecuteUtil {
    static HandleState execute(String exe, String msgIfSuccess, String msgIfError) {
        def proc = ['sh', '-c', exe].execute()
        def output = new StringBuffer()
        def error = new StringBuffer()
        proc.consumeProcessOutput(output, error)
        // freeTime 计数，每空闲6次输出一次到控制台，不然太频繁
        int freeTime = 0
        while (proc.isAlive()) {
            proc.waitFor(1000, TimeUnit.MILLISECONDS)
            if (output.length() > 0) {
                print output.toString()
                freeTime = 0
                output.delete(0, output.length())
            } else {
                freeTime += 1
                if (freeTime == 6) {
                    println '运行中，请稍候……'
                    freeTime = 0
                }
            }
        }
        proc.waitFor(200, TimeUnit.MILLISECONDS)
        if (output.length() > 0) {
            print output.toString()
            output.delete(0, output.length())
        }

        def rst = new HandleState()
        if (proc.exitValue() == 0) {
            println TextUtil.getColorString("------ ${msgIfSuccess} ------", TextUtil.Color.green)
        } else {
            println TextUtil.getColorString("错误信息：${error.toString()}", TextUtil.Color.red)
            println TextUtil.getColorString('！！！！！执行失败！！！！', TextUtil.Color.red)
            println TextUtil.getColorString(exe, TextUtil.Color.red)
            rst.stop = TextUtil.getColorString(msgIfError, TextUtil.Color.red)
        }
        return rst
    }
}
